#include "var_jni_utils.h"

void jVarSetNil(JNIEnv* env, jobject jval, jclass jvalClass)
{
	jmethodID method = env->GetMethodID(jvalClass, "SetNil", "()V");
	env->CallVoidMethod(jval, method);
}
int jVarType(JNIEnv* env, jobject jval, jclass jvalClass)
{
	jmethodID method = env->GetMethodID(jvalClass, "Type", "()B");
	return env->CallByteMethod(jval, method);
}

int jVarInt(JNIEnv* env, jobject jval, jclass jvalClass)
{
	jmethodID method = env->GetMethodID(jvalClass, "IntV", "()I");
	return env->CallIntMethod(jval, method);
}

int jVar2zVar(JNIEnv* env, jobject jval, jclass jvalClass,  zVar& zval)
{
	if (jvalClass == NULL)
	{
		return -1;
	}

	zval.SetNil();
	switch (jVarType(env, jval, jvalClass))
	{
	case EZVARType_nil:
		break;
	case EZVARType_false:
		zval.SetBool(false);
		break;
	case EZVARType_true:
		zval.SetBool(true);
		break;

	case EZVARType_int:
		zval.SetInt(jVarInt(env, jval, jvalClass));
		break;

	case EZVARType_str:
		{
			jmethodID method = env->GetMethodID(jvalClass, "Str", "()Ljava/lang/String;");
			jstring str = (jstring)(env->CallObjectMethod(jval, method));
			if(str != NULL)
			{
				jboolean isCopy=false;
				zval.SetStrL( (const char*)env->GetStringUTFChars(str, &isCopy), env->GetStringLength(str));
			}
		}
		break ;

	case EZVARType_table:
		break;
	default:
		assert(0);
		break;
	}
	return 0;
}

int zVar2jVar(JNIEnv* env, jobject jval, jclass jvalClass,  zVar& zval)
{
	if (jvalClass == NULL)
	{
		return -1;
	}
	jVarSetNil(env, jval, jvalClass);

	switch (zval.Type())
	{
	case EZVARType_nil:
		break;
	case EZVARType_false:
		{
			jmethodID method = env->GetMethodID(jvalClass, "SetBool", "(Z)V");
			env->CallVoidMethod(jval, method, false);
		}
		break;
	case EZVARType_true:
		{
			jmethodID method = env->GetMethodID(jvalClass, "SetBool", "(Z)V");
			env->CallVoidMethod(jval, method, true);
		}
		break;

	case EZVARType_int:
		{
			jmethodID method = env->GetMethodID(jvalClass, "SetInt", "(I)V");
			env->CallVoidMethod(jval, method, zval.IntV());
		}
		break;

	case EZVARType_str:
		{
			jstring str=env->NewStringUTF( (const char *)zval.Str());
			jmethodID method = env->GetMethodID(jvalClass, "SetStr", "(Ljava/lang/String;)V");
			env->CallVoidMethod(jval, method, str);
		}
		break ;

	case EZVARType_table:
		break;
	default:
		assert(0);
		break;
	}
	return 0;
}
